/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014-6-25         luwei
 */

package com.tianci.appstore;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;

import com.coocaa.framework.AppStoreApplication;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.DeviceModeMidType;
import com.coocaa.x.framework.app.SplashDialog;
import com.coocaa.x.framework.app.UpgradeManager;
import com.coocaa.x.framework.utils.FansChannelUpgrade;
import com.coocaa.x.framework.utils.LiteHandlerThread;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.tianci.appstore.audio.IAudio;
import com.tianci.appstore.controller.AppStoreAppListController;
import com.tianci.appstore.controller.AppStoreBaseController;
import com.tianci.appstore.controller.AppStoreMainPageController;
import com.tianci.appstore.ui.mainpage.SkyAppStoreMainPage;
import com.tianci.appstore.ui.widget.TipToast;

public class AppStoreActivity extends SkyBaseActivity {
    private Handler mHandler = new Handler();
    private SkyAppStoreMainPage mMainPage = null;
    private long mFirstBackTime = 0;
    public static String mFocusCategoryId = "";
    private ActivityManager mActivityManager = null;
    // defaultOpen = true -- 表示从主页点击“应用商城”来启动应用商城
    // defaultOpen = false - 表示从主页点击“我的应用”来启动应用商城
    public static boolean defaultOpen = true;
    public static long activityTime = 0;
    public static boolean dismisWelcome = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        dismisWelcome = false;
        LogUtils.d("test", "start activity!!");
        activityTime = System.currentTimeMillis();
        super.onCreate(savedInstanceState);
        AppStoreMainPageController.getInstance(getApplicationContext()).init();
        if (AppStoreBaseController.NETSTATUS) {
            LogUtils.d("test", "net is ok!  ");
            // AppStoreMainPageController.getInstance(getApplicationContext())
            // .getMainPageDataFromeWeb();
            AppStoreAppListController.getInstance().getCategoryListFromWeb();
        }
        mFocusCategoryId = getIntent().getStringExtra("category_id");
        LogUtils.d("test", "onCreate   the category id is " + mFocusCategoryId);
        if (mFocusCategoryId != null && mFocusCategoryId.equals(AppStoreMainPageController.MINE)) {
            defaultOpen = false;
        } else {
            defaultOpen = true;
        }
        if (getIntent().getAction() != null) {
            if (getIntent().getAction().equals("android.intent.action.MANAGE_PACKAGE_STORAGE")) {
                mFocusCategoryId = AppStoreMainPageController.GUANLI;
                defaultOpen = false;
            } else if (getIntent().getAction().equals("coocaa.intent.action.APP_STORE_MYAPPS")) {
                mFocusCategoryId = AppStoreMainPageController.MINE;
                defaultOpen = false;
            }
            LogUtils.d("test", "...action:" + getIntent().getAction());
        }
        LogUtils.d("test", "begin chose which way...");
        if (defaultOpen) {
//            ImageView imageView = new ImageView(this);
//            if (!LiteAppApplication.isMarketChannel() && !LiteAppApplication.isCommonChannel()) {
//                SkinManager.setBackground(imageView, R.drawable.cover);
//            }
//            RelativeLayout layout = new RelativeLayout(this);
//            SkinManager.setBackground(layout, R.drawable.ui_sdk_app_bg);
//            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
//                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//            params.addRule(RelativeLayout.CENTER_IN_PARENT);
//            imageView.setLayoutParams(params);
//            layout.addView(imageView);
//            setContentView(layout);

//            dismisWelcome = false;
            mMainPage = new SkyAppStoreMainPage(AppStoreActivity.this);
            initAudio();
            setContentView(mMainPage);
        } else {
            mMainPage = new SkyAppStoreMainPage(AppStoreActivity.this);
            initAudio();
            setContentView(mMainPage);
        }
        mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        post(new Runnable() {
            @Override
            public void run() {
                if (!LiteAppApplication.getFirstLaunch("FIRST_APP_OPEN")) {
                    try {
                        XServiceManager.getLiteCCConnectorService().firstStartAppPoints("FIRST_APP_OPEN");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                FansChannelUpgrade.insertOpenTimes(System.currentTimeMillis() / 1000);  //用秒来存储
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        dismisWelcome = false;
        setIntent(intent);
        mFocusCategoryId = getIntent().getStringExtra("category_id");

        if (mFocusCategoryId != null && mFocusCategoryId.equals(AppStoreMainPageController.MINE)) {
            defaultOpen = false;
        } else {
            defaultOpen = true;
        }
        if (getIntent().getAction() != null) {
            if (getIntent().getAction().equals("android.intent.action.MANAGE_PACKAGE_STORAGE")) {
                mFocusCategoryId = AppStoreMainPageController.GUANLI;
                defaultOpen = false;
            } else if (getIntent().getAction().equals("coocaa.intent.action.APP_STORE_MYAPPS")) {
                mFocusCategoryId = AppStoreMainPageController.MINE;
                defaultOpen = false;
            }
            LogUtils.d("test", "...action:" + getIntent().getAction());
        }
        if (mMainPage != null) {
            mMainPage.setCategoryFocus();
        }
    }

    private static boolean bShowSplashDialog = false;
    protected static SplashDialog splashDialog = null;


    @Override
    protected synchronized SplashDialog getSplashDialog() {
        LogUtils.d("Splash", "getSplashDialog defaultOpen:" + defaultOpen);
        if (defaultOpen && !bShowSplashDialog) {
            if (splashDialog == null)
                splashDialog = new AppStoreSplashDialog(this);
            bShowSplashDialog = true;
            return splashDialog;
        }
        return null;
    }

    @Override
    public void onResume() {
        if (mMainPage != null) {
            mMainPage.onResume();
        }
        super.onResume();

        CoocaaApplication.post(new Runnable() {
            @Override
            public void run() {
                if (defaultOpen && splashDialog != null && !splashDialog.useCache()) {
                    int time = 0;
                    while (time < 30) {
                        try {
                            Thread.sleep(100);
                            time++;
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (dismisWelcome && time > 10)
                            break;
                    }
                    LiteHandlerThread.postOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (splashDialog != null)
                                splashDialog.dismiss();
                        }
                    });
                }
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        LogUtils.d("test", "onWindowFocusChanged...");
        // if (hasFocus && mMainPage == null)
        // {
        // mMainPage = new SkyAppStoreMainPage(AppStoreActivity.this);
        // }
        super.onWindowFocusChanged(hasFocus);
    }

    // public void registerReceiver(){
    // LogUtils.d("intent", "registerReceiver");
    // TipToast.firstReceiver = true;
    // mNetChangeReceiver = new NetChangeReceiver();
    // IntentFilter netChangeFilter = new IntentFilter();
    // netChangeFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
    // this.registerReceiver(mNetChangeReceiver, netChangeFilter);
    // mInstalledReceiver = new InstalledReceiver();
    // IntentFilter installFilter = new IntentFilter();
    // installFilter.addAction("android.intent.action.PACKAGE_ADDED");
    // installFilter.addAction("android.intent.action.PACKAGE_REMOVED");
    // installFilter.addDataScheme("package");
    // this.registerReceiver(mInstalledReceiver, installFilter);
    // }
    //
    // public void unRegisterReceiver(){
    // LogUtils.d("intent", "unRegisterReceiver");
    // this.unregisterReceiver(mNetChangeReceiver);
    // this.unregisterReceiver(mInstalledReceiver);
    // }

    @Override
    protected void onDestroy() {
        // unRegisterReceiver();
        AppStoreMainPageController.getInstance(getApplicationContext()).destroy();
        if (mMainPage != null) {
            mMainPage.onDestory();
        }
        if (splashDialog != null) {
            splashDialog.dismiss();
            splashDialog = null;
        }
        bShowSplashDialog = false;
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:
                    long currentTime = System.currentTimeMillis();
                    if (currentTime - mFirstBackTime < 2000) {
                        TipToast.getInstance(this).clearToast();
                        DeviceModeMidType deviceType = LiteAppApplication.getDeviceModeMidType();
                        if (deviceType != null
                                && (deviceType.skytype.toLowerCase().contains("a43") || deviceType.skytype
                                .toLowerCase().contains("a55"))) {
                            long end = System.currentTimeMillis();
                            LogUtils.d("log", "appstore11  time:" + (int) (end - activityTime));
                            LogAPIForAppStore.AModuleUseTimelong(
                                    "com.tianci.appstore.AppStoreActivity", activityTime, end,
                                    (int) (end - activityTime));
                            try {
                                Thread.currentThread().sleep(200);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        activityTime = 0;
                        if (AppStoreApplication.needKillApplication) {

                            post(new Runnable() {
                                @Override
                                public void run() {
                                    UpgradeManager.exec("disable_dialog", null);
//                                    finish();
//                                    android.os.Process.killProcess(android.os.Process.myPid());
                                    System.exit(0);
                                }
                            });
                        } else {
                            post(new Runnable() {
                                @Override
                                public void run() {
                                    UpgradeManager.exec("disable_dialog", null);
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            finish();
                                        }
                                    });
                                }
                            });
                        }
                        // moveTaskToBack(false);
                        return true;
                    } else {
                        mFirstBackTime = System.currentTimeMillis();
                        // TipToast.getInstance(this).showToast(
                        // SkinManager.getResDrawable(R.drawable.toast_icon_exit),
                        // getString(R.string.press_again_to_exit));
                        if (mMainPage != null) {
                            if (!mMainPage.setFocusToRecommand()) {
                                DeviceModeMidType deviceType = LiteAppApplication
                                        .getDeviceModeMidType();
                                if (deviceType != null
                                        && (deviceType.skytype.toLowerCase().contains("a43") || deviceType.skytype
                                        .toLowerCase().contains("a55"))) {
                                    long end = System.currentTimeMillis();
                                    LogUtils.d("log", "appstore22  time:" + (int) (end - activityTime));
                                    LogAPIForAppStore.AModuleUseTimelong(
                                            "com.tianci.appstore.AppStoreActivity", activityTime,
                                            end, (int) (end - activityTime));
                                    try {
                                        Thread.currentThread().sleep(200);
                                    } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }
                                }
                                activityTime = 0;

                                post(new Runnable() {
                                    @Override
                                    public void run() {
                                        UpgradeManager.exec("disable_dialog", null);
                                        finish();
//                                        android.os.Process.killProcess(android.os.Process.myPid());
//                                        System.exit(0);
                                    }
                                });
                            }
                        }
                    }
                    return true;
                default:
                    break;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public String getName() {
        // TODO Auto-generated method stub
        return "应用圈应用主页面";
    }

    @Override
    public IAudio getAudioInterface() {
        return mMainPage.getAudioInterface();
    }
}
